var yz_pay = require("../../../mycomponent/yz_pay/yz_pay");

import Dialog from '../../../dist/dialog/dialog';
var app = getApp();
Page({
  behaviors: [yz_pay],
  data: {
    imagUrl: app.globalData.imgPath,
    language: "",
    isclick: true,
    order_id: "",
    store_id: "",
    orderData: null,
    balance: 0,
    payParams: "",
    info_form: {},
    order_sn: "",
    money: "",
    buttons: [],
    pay_sn: "订单编号",
    order_pay_id: "",
    uid: "",
    pid: "",
    status: "",

    //消费红包
    showPacket: false,
    redirectData: {},
    cbHref: {},
    is_cps: false,
    senceKey: "",

    orderType:"",

     //区别周边游支付和正常支付
     payTag:'',
     preOrderNo_show:false,
     preOrderNo:'',
     //当前选择的支付方式
     payMethods:'',
    //  支付协议弹窗
     IPAWatchTimeNum: 5,
     IPAToLower: false,//是否已触底
     disabledIPA: true //是否已完成阅读支付协议
  },
  fromChild(e){
    console.log(e);
    if(this.data.money=='0.00') {
      // 0元
      if(this.data.tag == 'auth'){
        //实名的支付
        this.authPay('54')
        return
      }
      this.sureBtn();
    }else {
      let datas = e.detail.submitArr;
      this.data.payMethods = datas.value;
      if(this.data.tag == 'auth'){
        //实名的支付
        this.authPay(datas.value)
        return
      }
      if(this.data.tag == "idShopApply" || this.data.tag == 'idShopSub'){
        // 圈商购买子id先请求生成订单记录接口↓
        this.idShopPay(datas.value)
        return
      }
      if(this.data.tag == 'tourAround') {
        if(!datas.need_password) {
          console.log('111111111');
          this.ordinary(this.data.order_sn, datas.value, datas);
        } else {
          this.rechargePay(datas.value, this.data.order_sn, this.data.order_sn, "tourAroundPay",datas); //走支付密码，不走周边游支付，避免重复支付
        }
        return;
      }
      this.confirm(datas);
    }
    
  },
  ordinary(order_sn,pay_type,data) {
    let query = {
      order_sn: order_sn,
      pay_type: pay_type
    };
    let _url = app.getNetAddresss('plugin.travel-around.frontend.payment.payment.pay');
    app._getNetWork({
      url: _url,
      data:query,
      success: (res)=> {
        if (res.data.result == 1) {
          console.log('111111123423');
          this.rechargePay(pay_type, res.data, order_sn, "tourAroundPay",data);
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "success",
            duration: 2000,
          });
          console.log("错误", res.data.msg);
        }
      },
    });
  },
  onClickHide() {
    this.setData({
      showPacket: false,
    });
    this.toRedirect();
  },
  toPacket() {
    wx.redirectTo({
      url: "/packageE/ConsumePacket/ConsumePacketSuccess/ConsumePacketSuccess?order_id=" + this.data.order_id.toString(),
    });
  },

  confirm(e) {
    let type = e.value;
    let btn = e;
    this.handlePay(btn, type);
  },

  onLoad: function (options) {
    wx.hideLoading();
    var that = this;
    let syinfo = wx.getEnterOptionsSync();
    // 获取场景值
    this.setData({
      senceKey: syinfo.scene,
      payMethods:''
    });
    console.log("options:", options);
    if(options.actualCount){
      this.setData({
        actualCount:options.actualCount
      })
    }
    if (options.iscps) {
      // 如果是聚合cps的话就跳转到卡密页面
      this.data.is_cps = true;
    }
    if (options.name) {
      that.setData({
        name: options.name,
      });
    }
    if(options.orderType){
      this.data.orderType = options.orderType;
    }
    if (options.pid) {
      that.setData({
        pid: options.pid,
      });
    }
    if (options.tag) {
      that.setData({
        tag: options.tag,
      });
    }
    that.setData({
      order_id: options.order_id,
    });
    if (options.status) {
      that.setData({
        status: options.status,
      });
    }
    if (options.store_id) {
      that.setData({
        store_id: options.store_id,
      });
    }

    if(options.tag == 'auth'){
      this.setData({
        money:options.price,
        tag:'auth'
      })
      this.authPayButton();
      return
    }
    if(options.tag == 'idShopApply' || options.tag == 'idShopSub'){
      this.setData({
        money:options.price,
        order_sn:options.ordersn,
        tag:options.tag,
        options:options
      })
      this.idShopApplyButton();
      return
    }
    if(options.tag == 'tourAround'){
      this.setData({
        order_sn:options.ordersn,
        payTag:options.tag,
      })
      console.log('11111111');
      this.tourAroundOrder(options.api);
      return
    }

    let yz_basic_info = wx.getStorageSync('yz_basic_info');
    if (yz_basic_info?.globalParameter?.is_open_shop_esign_v2 == 1) {
      this.getShopSignV2(); //商城电子合同2.0
    } else if (yz_basic_info?.globalParameter?.is_open_shop_esign == 1) {
      this.getShopSign(); //开启了商城电子合同
    } else {
      this.getMultipleOrderInfo();
    }
  },
  getMultipleOrderInfo(){
    // 多订单合并支付获取信息接口方法
    let _url = null;
    if (this.options.api) {
      if (this.options.api != "order.operation.pay") {
        _url = app.getNetAddresss(this.options.api);
      } else {
        _url = app.getNetAddresss("order.merge-pay");
      }
    } else {
      _url = app.getNetAddresss("order.merge-pay");
    }

    // console.log(options)
    if (this.options.status && this.options.status == 2) {
      // 合并支付
      if (typeof this.options.order_id == "string") {
        _url += "&order_ids=" + this.options.order_id;
      } else {
        _url += "&order_ids=" + JSON.parse(this.options.order_id).toString();
      }
    } else {
      _url += "&order_ids=" + this.options.order_id;
    }
    if(this.options.api=="plugin.water-machine.frontend.consumer.no-card-goods.index"){
      _url+="&device_no="+this.options.device_no;
    }
    
    app._getNetWork({
      url: _url,
      success: (res)=> {
        var _data = res.data.data;
        console.log("PayResult::::", _data);
        if (res.data.result == 1) {
          this.hanleIcon(_data);
          this.setData({
            // 购物车ID
            order_sn: _data.order_pay.pay_sn,
            balance: _data.member.credit2,
            money: _data.order_pay.amount.toFixed(2),
            uid: _data.order_pay.uid,
            buttons: _data.buttons,
            min_url: _data.min_redirect_url,
            mini_payment_agreement: _data.mini_payment_agreement
          });
          this.data.order_pay_id = _data.order_pay.id; // 支付id
          if(this.data.buttons && this.data.buttons.length == 0){
            wx.showToast({ title: '平台未开启任何支付方式，请联系客服', icon: 'none' });
          }
          if(this.data.mini_payment_agreement !== '') {
            wx.showToast({ title: '请下滑阅读协议', icon: 'error', duration: 3000 });
            this.setData({
              showPaymentAgreement: true
            });
            this.IPAInterval = setInterval(() => {
              this.setData({
                IPAWatchTimeNum: this.data.IPAWatchTimeNum - 1
              });
              if (this.data.IPAWatchTimeNum == 0 ) {
                clearInterval(this.IPAInterval); // 达到条件后清除计时器
                if(this.data.IPAToLower) {
                  this.setData({
                    disabledIPA: false
                  });
                }
              }
            }, 1000);
          }
        } else {
          Dialog.confirm({
            message: res.data.msg,
          }).then(() => {
              if(this.data.orderType){
                wx.redirectTo({
                  url: '/packageA/member/myOrder_v2/myOrder_v2?status=0&orderType='+this.data.orderType,
                });
              }else{
                wx.redirectTo({
                  url: "/packageG/index/index"
                });
              }
            })
            .catch(() => {
              // on cancel
            });
        
          // app.tips(res.data.msg)
          console.log("错误", res.data.msg);
        }
      },
    });
  },
  scrolltolowerPA(){
    this.data.IPAToLower = true;
    if(this.data.IPAToLower && this.data.IPAWatchTimeNum == 0) {
      this.setData({
        disabledIPA: false
      });
    }
  },
  payArtNext(){
    if(this.data.disabledIPA) return;
    this.setData({
      showPaymentAgreement: false
    });
  },
  cancelPA(){
    wx.navigateBack({
      delta:1,
      fail:()=>{
        wx.reLaunch({
          url: '/packageG/index/index',
        })
      }
    })
  },
  getShopSign() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.shop-esign.frontend.contract.get-order-contract'),
      data: {
        order_ids: this.options.order_id
      },
      success: (res)=> {
        var _data = res.data;
        if (res.data.result == 1) {
          let flag = false;
          _data.data.map(item => {
            if (item.need_sign === 1 && item.contract_id && !flag) {
              flag = true;
              wx.showModal({
                title: '提示',
                content: `您的订单(订单号:${item.order_sn})在支付前需要签署电子合同`,
                showCancel: false,
                success (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: `/packageH/signPage/signPage?id=${item.contract_id}&fromOrder=1`,
                    });
                  }
                }
              })
            }
          });

          if (!flag) {
            this.getMultipleOrderInfo();
          }
        } else {
          this.getMultipleOrderInfo();
        }
      },
    });
  },
  getShopSignV2() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.shop-esign-v2.frontend.controllers.index.needSign'),
      data: {
        order_id: this.options.order_id
      },
      success: (res)=> {
        var _data = res.data;
        if (res.data.result == 1) {
          if (_data.data.need_sign) {
            wx.showModal({
              title: '提示',
              content: `您的订单在支付前需要签署电子合同`,
              showCancel: false,
              success: (res)=> {
                if (res.confirm) {
                  wx.navigateTo({
                    url: `/packageH/sign_shopV2/index/index?scene=1&order_id=${this.options.order_id}`,
                  });
                }
              }
            })
            return;
          }
          this.getMultipleOrderInfo();
        } else {
          this.getMultipleOrderInfo();
        }
      },
    });
  },
  authPay(payId){
    let that = this;
    let _url = app.getNetAddresss('plugin.real-name-auth.frontend.pay.pay');
    app._getNetWork({
      url: _url,
      data:{
        pay_id:payId,
        pay_amount:this.data.money,
        pay_sn:this.data.order_sn
      },
      success: (res)=> {
        if (res.data.result == 1) {
          if(payId == '54'){
            wx.navigateBack({
              delta: 1,
            })
            return
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 1000,
              success:function(resdata){
                that.rechargePay(payId,res.data,res.data.data.pay_sn)
              }
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "success",
            duration: 2000,
          });
          console.log("错误", res.data.msg);
        }
      },
    });
  },
  //周边游支付
  tourAroundOrder(api){
    console.log(api);
    let json = {
      order_sn: this.data.order_sn
    };
    console.log(json);
    let url = app.getNetAddresss(api);
    app._getNetWork({
      url: url,
      data:json,
      success: (res)=> {
        var _data = res.data.data;
        if (res.data.result == 1) {
          console.log('执行');
          console.log(_data);
          this.setData({
            // 购物车ID
            order_sn: _data.order?.order_sn,
            balance: _data?.credit2,
            money: _data.order?.order_price,
            uid: _data.order?.id,
            buttons: _data.buttons,
            order_pay_id: _data.order?.id
          });
          console.log(this.data.buttons);
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "success",
            duration: 2000,
          });
          console.log("错误", res.data.msg);
        }
      },
    });
  },
  async idShopApplyButton(){
    let {data} = await app._getNetWork({
      url: app.getNetAddresss("plugin.project-party.frontend.controllers.child-id.getButtons"),
      data: {
        price:this.data.money,
        pay_sn:this.data.options.ordersn
      }
    })
    let res = data.data;
    if(data.result){
      this.hanleIcon(data.data);
      this.setData({
        buttons:res.buttons,
      })
    }else{
      wx.navigateBack({
        delta:1,
        fail:()=>{
          wx.reLaunch({
            url: '/packageG/index/index',
          })
        }
      })
    }
  },
  authPayButton(){
    let _url = app.getNetAddresss('plugin.real-name-auth.frontend.pay.getPayButton');
    app._getNetWork({
      url: _url,
      success: (res)=> {
        var _data = res.data.data;
        if (res.data.result == 1) {
          console.log(_data,'ddddddddddd')
          this.hanleIcon(_data);
          this.setData({
            order_sn:_data.pay_sn,
            buttons:_data.buttons
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "success",
            duration: 2000,
          });
          console.log("错误", res.data.msg);
        }
      },
    });
  },
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    if(this.data.payMethods == 132){
      // 获取第三方小程序支付成功回来的参数
      const { referrerInfo } = wx.getEnterOptionsSync();
      // 微信小程序汇聚plus支付-汇聚插件第三方小程序跳转回调携带支付是否成功参数
      if ( referrerInfo.extraData?.status == 1 ){
        this.checkoutConsumePacket();
      } else {
        app.tips('支付失败')
        this.data.isPayClick = false;
      }
    }
  },
  onHide: function () {
    if(this.IPAInterval) clearInterval(this.IPAInterval)
    this.data.isPayClick = false;
    // 页面隐藏
    if(this.data.options.tag == "idShopApply" || this.data.options.tag == "idShopSub"){
      this.releaseChildId('hide')
    }
  },
  onUnload: function () {
    if(this.data.options.tag == "idShopApply" || this.data.options.tag == "idShopSub"){
      this.releaseChildId()
    }
    // 页面关闭
    if(this.IPAInterval) clearInterval(this.IPAInterval)
    if (this.data.tag == "activity") {
      wx.navigateBack({
        delta: 1,
      });
    }
    if(this.data.name == 'Myshaky'){
      wx.navigateBack({
        delta: 1,
      });
    }
  },
});
